package com.example.springboot.utils.encrypt;

import com.gaokao.volunteer.utils.utilabstract.BaseConstant;
import org.apache.commons.lang3.StringUtils;

import java.security.MessageDigest;

/**
 * @Description: TODO MD5双重加密
 * @Date: 2018-12-14 14:44:38
 * @author: fengyuan
 */
public class MD5SaltUtil {

    private String inStr;

    private MessageDigest md5;

    public MD5SaltUtil(String inStr) {
        this.inStr = inStr;
        try {
            this.md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
        }
    }

    private String compute() {
        char[] charArray = this.inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];
        for (int i = 0; i < charArray.length; i++) {
            byteArray[i] = (byte) charArray[i];
        }
        byte[] md5Bytes = this.md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    /**
     * 用户登录时输入的密码与数据库加密密码进行比较
     *
     * @param plaintextPwd 用户输入的明文密码
     * @param salt         随机“佐料” salt
     * @param md5Pwd       数据库中加密后的密码
     * @return
     */
    public static boolean compare(String plaintextPwd, String salt, String md5Pwd) {
        MD5SaltUtil md5 = new MD5SaltUtil(plaintextPwd);
        // 用MD5第一次加密
        String pwd = md5.compute();
        pwd = pwd + salt;
        // 再次用MD5加密
        MD5SaltUtil m = new MD5SaltUtil(pwd);
        // 得到最终密文
        String npwd = m.compute().toUpperCase();
        return npwd.equals(md5Pwd);
    }

    /**
     * 密码盐 加密
     *
     * @param plaintextPwd 明文密码
     * @param salt         用户名
     * @return
     */
    public static String enCode(String plaintextPwd, String salt) {
        plaintextPwd = StringUtils.isBlank(plaintextPwd) ? BaseConstant.DEFAULT_PWD : plaintextPwd;
        MD5SaltUtil md5 = new MD5SaltUtil(plaintextPwd);
        // 用MD5第一次加密
        String pwd = md5.compute();
        pwd = pwd + salt;
        // 再次用MD5加密
        MD5SaltUtil m = new MD5SaltUtil(pwd);
        // 得到最终密文
        String npwd = m.compute().toUpperCase();
        return npwd;
    }

}
